<template>
  <a-modal
    class="formModal editor"
    :title="`${
      isAdd
        ? $t('form.profile_edu.add_title')
        : $t('form.profile_edu.change_title')
    }`"
    v-model:open="modalVisible"
    @cancel="close"
    :footer="null"
  >
    <a-form layout="vertical" ref="formRef" :model="formState">
      <a-form-item
        class="span-2"
        :label="$t('form.profile_edu.form.item_1.label')"
        name="date_value"
        :rules="[
          {
            required: true,
            message: $t('form.profile_edu.form.item_1.rules.error_1'),
            trigger: 'blur',
          },
        ]"
      >
        <a-range-picker
          v-model:value="formState.date_value"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
      </a-form-item>
      <a-form-item
        :label="$t('form.profile_edu.form.item_2.label')"
        name="company_title"
        :rules="[
          {
            required: true,
            message: $t('form.profile_edu.form.item_2.rules.error_1'),
            trigger: 'blur',
          },
        ]"
        ><a-input
          :maxlength="50"
          v-model:value.trim="formState.company_title"
          :placeholder="$t('form.profile_edu.form.item_2.rules.error_1')"
          allowClear
        ></a-input>
      </a-form-item>
      <a-form-item
        :label="$t('form.profile_edu.form.item_3.label')"
        name="position_name"
        :rules="[
          {
            required: true,
            message: $t('form.profile_edu.form.item_3.rules.error_1'),
            trigger: 'blur',
          },
        ]"
      >
        <a-input
          :maxlength="50"
          v-model:value.trim="formState.position_name"
          :placeholder="$t('form.profile_edu.form.item_3.rules.error_1')"
          allowClear
        ></a-input>
      </a-form-item>
      <a-form-item
        :label="$t('form.profile_edu.form.item_4.label')"
        name="job_description"
        :rules="[
          {
            required: true,
            message: $t('form.profile_edu.form.item_4.rules.error_1'),
            trigger: 'blur',
          },
        ]"
      >
        <div style="min-width: 1px" class="flex-1">
          <Editor
            type="modal"
            class="editor"
            :placeholder="$t('form.profile_edu.form.item_4.rules.error_1')"
            v-model="formState.job_description"
          />
        </div>
      </a-form-item>
    </a-form>
    <div class="footer-btns">
      <a-button @click="close">{{ $t("btnText.cancel") }}</a-button>
      <a-button type="primary" :loading="isSubmitting" @click="submit">{{
        $t("btnText.save")
      }}</a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, nextTick, getCurrentInstance, inject } from "vue";
import type { ExperienceAddParams } from "../../types/profile";
import {
  ExperienceUrl,
  postExperienceCreate,
  postExperienceUpdate,
} from "../../api/profile";
import { message } from "ant-design-vue";
const modalVisible = ref(false);

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const props = defineProps<{
  data: Object;
  isAdd: boolean;
}>();

const close = () => {
  formRef.value.resetFields();
  modalVisible.value = false;
};
const show = () => {
  modalVisible.value = true;
  if (props.isAdd) {
    Object.keys(formState.value).forEach((key) => {
      formState.value[key] = "";
    });
  } else {
    formState.value.id = props.data.id;
    formState.value.date_value = [
      [props.data.start_year, props.data.start_month, "01"].join("-"),
      [props.data.end_year, props.data.end_month, "01"].join("-"),
    ];
    formState.value.company_title = props.data.company_title;
    formState.value.position_name = props.data.position_name;
    formState.value.job_description = props.data.job_description;
  }
};

defineExpose({
  close,
  show,
});

// ===============form state================
const formRef = ref();

const formState = ref({
  date_value: [""],
  start_year: "",
  start_month: "",
  end_year: "",
  end_month: "",
  company_title: "",
  position_name: "",
  job_description: "",
});

const setDate = () => {
  formState.value.start_year = formState.value.date_value[0].split("-")[0];
  formState.value.start_month = formState.value.date_value[0].split("-")[1];
  formState.value.end_year = formState.value.date_value[1].split("-")[0];
  formState.value.end_month = formState.value.date_value[1].split("-")[1];
};

const lang = inject("lang");
const emits = defineEmits(["complete"]);
const isSubmitting = ref(false);
const submit = () => {
  formRef.value.validate().then(async () => {
    setDate();
    isSubmitting.value = true;
    let { date_value, ...params } = formState.value;
    params = { ...params, lang: lang.value };
    if (props.isAdd) {
      let res = await postExperienceCreate(ExperienceUrl.eduCreate, params);
      isSubmitting.value = false;
      if (res.code === 200) {
        message.success($t("message.success.add"));
        close();
        emits("complete");
      } else {
        message.error($t("message.error.add"));
        close();
      }
    } else {
      let res = await postExperienceUpdate(ExperienceUrl.eduUpdate, params);
      isSubmitting.value = false;
      if (res.code === 200) {
        message.success($t("message.success.update"));
        close();
        emits("complete");
      } else {
        message.error($t("message.error.update"));
        close();
      }
    }
  });
};
</script>
<style scoped lang="less"></style>
